//
//  AddressAlertView.m
//  Peso Guide
//
//  Created by macbook on 2025/6/13.
//

#import "AddressAlertView.h"

@interface AddressAlertView ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIView *grayView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIImageView *backImg;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) BaseTableView *tableView;

// 新增属性
@property (nonatomic, strong) NSMutableArray *displayData; // 当前显示的数据
@property (nonatomic, strong) NSDictionary *selectedDistrict; // 选中的三级地区
@property (nonatomic, strong) NSDictionary *selectedCity; // 选中的二级地区
@property (nonatomic, strong) NSDictionary *selectedProvince; // 选中的一级地区
@property (nonatomic, assign) NSInteger expandedProvinceIndex; // 当前展开的一级索引
@property (nonatomic, assign) NSInteger expandedCityIndex; // 当前展开的二级索引

@end

@implementation AddressAlertView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // 初始化视图
        _grayView = [PesoKit createViewWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) backGroundColor:[UIColor colorWithHexString:@"#000000" alpha:0.7]];
        [self addSubview:_grayView];
        
        _backImg = [PesoKit createImageViewWithFrame:CGRectMake((KScreenWidth-301)/2.0, (KScreenHeight-461)/2.0-20, 301, 461) imageNamed:@"ic_identity_alert_back_long"];
        _backImg.userInteractionEnabled = YES;
        _backImg.clipsToBounds = YES;
        _backImg.layer.cornerRadius = 15.0f;
        [self addSubview:_backImg];
        
        _titleLabel = [PesoKit createLabelWithFrame:CGRectMake(0, 0, _backImg.width, 60) backGroundColor:[UIColor clearColor] text:[Lang set:@"Please select an address"] textColor:ColorHex(@"#000000") font:FONT(FontWeightStyleMedium, 20)];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        [_backImg addSubview:_titleLabel];
        
        _confirmButton = [PesoKit createButtonWithFrame:CGRectMake((_backImg.width-214)/2.0, _backImg.height-32-44, 214, 44) backGroundColor:ColorHex(@"#FE7133") title:[Lang set:@"Confirm"] titleColor:ColorHex(@"#FFFFFF") font:FONT(FontWeightStyleMedium, 18)];
        [_confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
        _confirmButton.clipsToBounds = YES;
        _confirmButton.layer.cornerRadius = 22.0f;
        [_backImg addSubview:_confirmButton];
        
        _closeButton = [[UIButton alloc] initWithFrame:CGRectMake((KScreenWidth-26)/2.0, _backImg.bottom+16, 26, 26)];
        [_closeButton setBackgroundImage:[UIImage imageNamed:@"ic_identity_close"] forState:0];
        [_closeButton addTarget:self action:@selector(closeButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_closeButton];
        
        [_backImg addSubview:self.tableView];
        
        // 初始化状态
        _expandedProvinceIndex = -1;
        _expandedCityIndex = -1;
        _displayData = [NSMutableArray array];
        
        // 获取本地存储的三级城市列表json
        NSString *addressJson = [[NSUserDefaults standardUserDefaults] objectForKey:@"app_city_json"];
        self.dataArray = [NSMutableArray safeArrayWithArray:[AppTools arrayWithJsonString:addressJson]];
        
        // 构建初始显示数据
        [self buildInitialDisplayData];
        
        // 如果本地没有存储 则请求拉取三级城市列表
        if (self.dataArray.count == 0) {
            [[AWHttpService service] getWithUrl:@"/trains/experience" params:@{} succ:^(id  _Nonnull responseObject) {
                if (SUCCESS) {
                    NSDictionary *associating = [NSDictionary safeDictionaryWithDictionary:[responseObject safeObjectForKey:@"associating"]];
                    NSArray *addressArray = [NSArray safeArrayWithArray:[associating safeObjectForKey:@"below"]];
                    self.dataArray = [NSMutableArray safeArrayWithArray:addressArray];
                    
                    // 构建显示数据
                    [self buildInitialDisplayData];
                    [self.tableView reloadData];
                    
                    NSString *json = [AppTools jsonStringWithNSArray:addressArray];
                    [[NSUserDefaults standardUserDefaults] setObject:json forKey:@"app_city_json"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            } fail:^(NSInteger errorType, id  _Nonnull error) {
            }];
        }
    }
    return self;
}

// 构建初始显示数据（只显示一级）
- (void)buildInitialDisplayData {
    [_displayData removeAllObjects];
    for (NSDictionary *province in self.dataArray) {
        [_displayData addObject:@{
            @"type": @"province",
            @"data": province,
            @"expanded": @NO
        }];
    }
}

// 展开或收起省份
- (void)toggleProvinceAtIndex:(NSInteger)index {
    NSMutableDictionary *provinceDict = [NSMutableDictionary dictionaryWithDictionary:_displayData[index]];
    BOOL isExpanded = [provinceDict[@"expanded"] boolValue];
    
    if (isExpanded) {
        // 收起：删除该省份下的所有城市
        NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet indexSet];
        for (NSInteger i = index + 1; i < _displayData.count; i++) {
            NSDictionary *item = _displayData[i];
            if ([item[@"type"] isEqualToString:@"province"]) break;
            [indexesToRemove addIndex:i];
        }
        [_displayData removeObjectsAtIndexes:indexesToRemove];
        
        provinceDict[@"expanded"] = @NO;
        _displayData[index] = provinceDict;
        _expandedProvinceIndex = -1;
        _expandedCityIndex = -1;
    } else {
        // 收起之前展开的省份
        if (_expandedProvinceIndex != -1 && _expandedProvinceIndex != index) {
            [self toggleProvinceAtIndex:_expandedProvinceIndex];
        }
        
        // 展开：添加该省份下的城市
        NSDictionary *provinceData = provinceDict[@"data"];
        NSArray *cities = [NSArray safeArrayWithArray:provinceData[@"below"]];
        
        NSMutableArray *cityArray = [NSMutableArray array];
        for (NSDictionary *city in cities) {
            [cityArray addObject:@{
                @"type": @"city",
                @"data": city,
                @"expanded": @NO,
                @"provinceIndex": @(index)
            }];
        }
        
        // 插入到当前省份后面
        NSRange range = NSMakeRange(index + 1, cityArray.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [_displayData insertObjects:cityArray atIndexes:indexSet];
        
        provinceDict[@"expanded"] = @YES;
        _displayData[index] = provinceDict;
        _expandedProvinceIndex = index;
        _expandedCityIndex = -1;
    }
}

// 展开或收起城市
- (void)toggleCityAtIndex:(NSInteger)index {
    NSMutableDictionary *cityDict = [NSMutableDictionary dictionaryWithDictionary:_displayData[index]];
    BOOL isExpanded = [cityDict[@"expanded"] boolValue];
    NSInteger provinceIndex = [cityDict[@"provinceIndex"] integerValue];
    
    if (isExpanded) {
        // 收起：删除该城市下的所有区域
        NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet indexSet];
        for (NSInteger i = index + 1; i < _displayData.count; i++) {
            NSDictionary *item = _displayData[i];
            if (![item[@"type"] isEqualToString:@"district"]) break;
            [indexesToRemove addIndex:i];
        }
        [_displayData removeObjectsAtIndexes:indexesToRemove];
        
        cityDict[@"expanded"] = @NO;
        _displayData[index] = cityDict;
        _expandedCityIndex = -1;
    } else {
        // 收起之前展开的城市
        if (_expandedCityIndex != -1 && _expandedCityIndex != index) {
            [self toggleCityAtIndex:_expandedCityIndex];
        }
        
        // 展开：添加该城市下的区域
        NSDictionary *cityData = cityDict[@"data"];
        NSArray *districts = [NSArray safeArrayWithArray:cityData[@"below"]];
        
        NSMutableArray *districtArray = [NSMutableArray array];
        for (NSDictionary *district in districts) {
            [districtArray addObject:@{
                @"type": @"district",
                @"data": district,
                @"provinceIndex": @(provinceIndex),
                @"cityIndex": @(index)
            }];
        }
        
        // 插入到当前城市后面
        NSRange range = NSMakeRange(index + 1, districtArray.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [_displayData insertObjects:districtArray atIndexes:indexSet];
        
        cityDict[@"expanded"] = @YES;
        _displayData[index] = cityDict;
        _expandedCityIndex = index;
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _displayData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"AddressCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    // 清除旧内容
    cell.textLabel.text = nil;
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.textLabel.font = FONT(FontWeightStyleRegular, 15);
    cell.textLabel.textColor = ColorHex(@"#0E1D31");
    
    NSDictionary *item = _displayData[indexPath.row];
    NSDictionary *data = item[@"data"];
    NSString *type = item[@"type"];
    
    // 设置文本
    cell.textLabel.text = data[@"restriction"];
    
    // 设置缩进
    if ([type isEqualToString:@"province"]) {
        cell.indentationLevel = 0;
    } else if ([type isEqualToString:@"city"]) {
        cell.indentationLevel = 1;
    } else if ([type isEqualToString:@"district"]) {
        cell.indentationLevel = 2;
    }
    
    // 设置展开图标
    if ([type isEqualToString:@"province"] || [type isEqualToString:@"city"]) {
        cell.accessoryType = [item[@"expanded"] boolValue] ?
                             UITableViewCellAccessoryNone :
                             UITableViewCellAccessoryDisclosureIndicator;
    }
    
    // 设置选中状态
    if ([type isEqualToString:@"district"]) {
        if (self.selectedDistrict && [self.selectedDistrict[@"causes"] integerValue] == [data[@"causes"] integerValue]) {
            cell.textLabel.font = FONT(FontWeightStyleMedium, 16);
            cell.textLabel.textColor = ColorHex(@"#1A7A35");
        }
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *item = _displayData[indexPath.row];
    NSString *type = item[@"type"];
    
    if ([type isEqualToString:@"province"]) {
        [self toggleProvinceAtIndex:indexPath.row];
        [self.tableView reloadData];
    }
    else if ([type isEqualToString:@"city"]) {
        [self toggleCityAtIndex:indexPath.row];
        [self.tableView reloadData];
    }
    else if ([type isEqualToString:@"district"]) {
        // 选中区域
        self.selectedDistrict = item[@"data"];
        
        // 获取对应的省和市
        NSInteger provinceIndex = [item[@"provinceIndex"] integerValue];
        NSInteger cityIndex = [item[@"cityIndex"] integerValue];
        
        self.selectedProvince = _displayData[provinceIndex][@"data"];
        self.selectedCity = _displayData[cityIndex][@"data"];
        
        [self.tableView reloadData];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.0f;
}

- (BaseTableView *)tableView {
    if (!_tableView) {
        _tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(16, 60, 301-16*2, 381-40-16-16) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }
    return _tableView;
}

- (void)confirmButtonClick {
    if (!self.selectedDistrict) {
        // 提示选择
        [SVProgressHUD showErrorWithStatus:@"please select"];
        [SVProgressHUD dismissWithDelay:3.0f];

        return;
    }
    
    // 准备输出结果
    NSDictionary *result = @{
        @"province": @{
            @"restriction": self.selectedProvince[@"restriction"] ?: @"",
            @"causes": self.selectedProvince[@"causes"] ?: @0
        },
        @"city": @{
            @"restriction": self.selectedCity[@"restriction"] ?: @"",
            @"causes": self.selectedCity[@"causes"] ?: @0
        },
        @"district": @{
            @"restriction": self.selectedDistrict[@"restriction"] ?: @"",
            @"causes": self.selectedDistrict[@"causes"] ?: @0
        }
    };
    
    DLog(@"chooseAddress: %@", result);
    
    if (self.selectionHandler) {
        self.selectionHandler(result);
    }
    
    // 这里可以回调给外部或处理结果
    [self removeFromSuperview];
}

- (void)closeButtonClick {
    [self removeFromSuperview];
}

@end
